#!/bin/bash
{
	#////////////////////////////////////
	# DietPi AutoStart Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Filename: /boot/dietpi/dietpi-autostart
	#
	# Usage:
	# - dietpi-autostart		Menu system
	# - dietpi-autostart <int>	Apply autostart index non-interactively
	#////////////////////////////////////

	# Import DietPi-Globals --------------------------------------------------------------
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-AutoStart'
	G_CHECK_ROOT_USER
	G_CHECK_ROOTFS_RW
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	# Grab input (valid integer)
	disable_error=1 G_CHECK_VALIDINT "$1" -1 && INPUT=$1 || INPUT=-1

	# Global variables and functions
	readonly FP_SETTINGS='/boot/dietpi/.dietpi-autostart_index'
	ID_AUTOSTART=0
	Apply_Boot_Index()
	{
		# Disable all autostart options first
		# - LightDM
		rm -f /etc/systemd/system/display-manager.service /etc/lightdm/lightdm.conf.d/dietpi-autologin.conf
		[[ -d '/etc/lightdm/lightdm.conf.d' ]] && rmdir --ignore-fail-on-non-empty /etc/lightdm/lightdm.conf.d

		# - Amiberry
		systemctl disable --now amiberry &> /dev/null
		if (( $G_HW_MODEL < 10 ))
		then
			sed -i '/^[[:blank:]]*boot_delay=0/d' /boot/config.txt
			sed -i 's/[[:blank:]]*loglevel=3//' /boot/cmdline.txt
			sed -i 's/console=tty3/console=tty1/' /boot/cmdline.txt
		fi

		# - Custom script
		if [[ -f '/etc/systemd/system/dietpi-autostart_custom.service' ]]
		then
			systemctl disable --now dietpi-autostart_custom
			rm -R /etc/systemd/system/dietpi-autostart_custom.service*
		fi

		# - Auto login
		local fp_svc1='/etc/systemd/system/getty@tty1.service.d'
		if [[ -d $fp_svc1 ]]
		then
			[[ -f $fp_svc1/dietpi-autologin.conf ]] && rm $fp_svc1/dietpi-autologin.conf
			rmdir --ignore-fail-on-non-empty $fp_svc1
		fi
		local fp_svc2='/etc/systemd/system/console-getty.service.d'
		if [[ -d $fp_svc2 ]]
		then
			[[ -f $fp_svc2/dietpi-autologin.conf ]] && rm $fp_svc2/dietpi-autologin.conf
			rmdir --ignore-fail-on-non-empty $fp_svc2
		fi

		#----------------------------------------------------------------------
		# Enable selected autostart option
		# - Custom script, service without auto login: https://github.com/MichaIng/DietPi/issues/1024
		if (( $ID_AUTOSTART == 14 ))
		then
			cat << '_EOF_' > /etc/systemd/system/dietpi-autostart_custom.service
[Unit]
Description=DietPi-Autostart (Custom /var/lib/dietpi/dietpi-autostart/custom.sh)
Requisite=dietpi-boot.service
After=dietpi-boot.service dietpi-postboot.service rc-local.service
ConditionPathExists=/var/lib/dietpi/dietpi-autostart/custom.sh

[Service]
Type=idle
RemainAfterExit=yes
StandardOutput=tty
ExecStartPre=/bin/chmod +x /var/lib/dietpi/dietpi-autostart/custom.sh
ExecStartPre=/bin/echo 'Starting DietPi-Autostart (Custom) script...'
ExecStart=/var/lib/dietpi/dietpi-autostart/custom.sh

[Install]
WantedBy=multi-user.target
_EOF_
			G_EXEC systemctl enable dietpi-autostart_custom

		# - Amiberry fast boot via enabled service
		elif (( $ID_AUTOSTART == 6 ))
		then
			G_EXEC systemctl enable amiberry
			# Enable systemd-logind to have a login console ready after exiting Amiberry from fastboot, requires dbus
			G_EXEC_NOHALT=1 G_AG_CHECK_INSTALL_PREREQ dbus
			G_EXEC_NOHALT=1 G_EXEC systemctl unmask systemd-logind

			# RPi tweaks
			if (( $G_HW_MODEL < 10 ))
			then
				G_CONFIG_INJECT 'boot_delay=' 'boot_delay=0' /boot/config.txt
				grep -qi ' logo.nologo' /boot/cmdline.txt || G_EXEC sed -i 's/rootwait/rootwait logo.nologo/' /boot/cmdline.txt
				grep -qi ' loglevel=3' /boot/cmdline.txt || G_EXEC sed -i 's/rootwait/rootwait loglevel=3/' /boot/cmdline.txt
				grep -qi ' console=tty3' /boot/cmdline.txt || G_EXEC sed -i 's/console=tty1/console=tty3/' /boot/cmdline.txt
			fi

		# - LightDM: Install only if startx (a desktop) is already installed. This is re-applied by dietpi-software after install automatically.
		elif (( $ID_AUTOSTART == 16 ))
		then
			command -v X > /dev/null || { G_WHIP_MSG '[FAILED] No X server has been found\n\nLightDM requires an X server. Please install a desktop or other X application first.'; return 1; }
			G_AG_CHECK_INSTALL_PREREQ lightdm
			# graphical.target Wants=display-manager.service
			G_EXEC ln -sf /lib/systemd/system/lightdm.service /etc/systemd/system/display-manager.service

		# - Enable autologin
		elif (( $ID_AUTOSTART > 0 ))
		then
			# Autologin user
			local user=$(sed -n '/^[[:blank:]]*AUTO_SETUP_AUTOSTART_LOGIN_USER=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
			[[ $user ]] || user='root'
			# Allow selection in interactive mode
			if (( $INPUT == -1 ))
			then
				# Only users with ID >= 1000 (+ root) and with valid login shell
				# Coders NB: read/mapfile cannot be easily used here since we need to parse multiple lines and split at newline AND space.
				# shellcheck disable=SC2207
				G_WHIP_MENU_ARRAY=('root' 'UID:0' $(mawk -F: '$3 >= 1000 && $7 ~ /^\/bin\/.*sh$/{print $1" UID:"$3}' /etc/passwd))
				G_WHIP_DEFAULT_ITEM=$user

				# Add hint about possibly required permissions in all cases but LightDM-based autologin
				local permissions_hint=
				(( $ID_AUTOSTART == 2 )) || permissions_hint='\nNB: You might need to grant the user permissions to run the chosen autostart option.'
				G_WHIP_MENU "Please choose a user to login with.$permissions_hint\n\nCurrent choice: $user" && user=$G_WHIP_RETURNED_VALUE || user='root'

				# Apply choice to dietpi.txt
				G_CONFIG_INJECT 'AUTO_SETUP_AUTOSTART_LOGIN_USER=' "AUTO_SETUP_AUTOSTART_LOGIN_USER=$user" /boot/dietpi.txt

			# Do sanity check, when applying dietpi.txt entry in non-interactive mode
			elif ! grep -qE "^$user:[^:]*:(0|[1-9][0-9][0-9][0-9]+):.*:/bin/[^:]*sh$" /etc/passwd
			then
				G_DIETPI-NOTIFY 1 "User \"$user\" does not exist, is a system user or does not have a valid login shell. Reverting to \"root\"."
				user='root'
			fi

			# User-specific steps, e.g. permissions: https://github.com/MichaIng/DietPi/issues/3351
			if [[ $user == 'root' ]]
			then
				:

			# - Kodi
			elif (( $ID_AUTOSTART == 1 ))
			then
				G_EXEC usermod -aG video $user
				getent group render > /dev/null && G_EXEC usermod -aG render $user

			# - Desktop autologin: As non-root user, it's LightDM-based
			elif (( $ID_AUTOSTART == 2 ))
			then
				command -v X > /dev/null || { G_WHIP_MSG '[FAILED] No X server has been found\n\nDesktop autologin requires an X server. Please install a desktop or other X application first.'; return 1; }
				G_AG_CHECK_INSTALL_PREREQ lightdm
				# graphical.target Wants=display-manager.service
				G_EXEC ln -sf /lib/systemd/system/lightdm.service /etc/systemd/system/display-manager.service

				[[ -d '/etc/lightdm/lightdm.conf.d' ]] || G_EXEC mkdir -p /etc/lightdm/lightdm.conf.d
				echo -e "[Seat:*]\nautologin-user=$user" > /etc/lightdm/lightdm.conf.d/dietpi-autologin.conf

			# - systemd service control: Interactive authentication requires policykit-1 (> libpam-systemd > dbus) + systemd-logind
			elif [[ $ID_AUTOSTART == 8 ]]
			then
				G_EXEC systemctl unmask systemd-logind
				G_AG_CHECK_INSTALL_PREREQ policykit-1

			# - CAVA: Copy config and font from root, created on install
			elif (( $ID_AUTOSTART == 10 ))
			then
				[[ ! -d ~$user/.config/cava ]] && mkdir -p ~$user/.config && cp /root/.config/cava ~$user/.config/cava && chown -R $user: ~$user/.config
				[[ ! -f ~$user/cava.psf ]] && cp /root/cava.psf ~$user/cava.psf && chown $user: ~$user/cava.psf
			fi

			# Apply to TTY1 getty: Skip for LightDM-based autologin
			if [[ $ID_AUTOSTART != 2 || $user == 'root' ]]
			then
				G_EXEC mkdir -p $fp_svc1 $fp_svc2
				cat << _EOF_ > $fp_svc1/dietpi-autologin.conf
[Service]
ExecStart=
ExecStart=-/sbin/agetty -a $user -J %I \$TERM
_EOF_
				cat << _EOF_ > $fp_svc2/dietpi-autologin.conf
[Service]
ExecStart=
ExecStart=-/sbin/agetty -a $user -J -s console 115200,38400,9600 \$TERM
_EOF_
			fi
		else
			[[ -f $FP_SETTINGS ]] && G_EXEC rm $FP_SETTINGS
		fi

		# Save boot index, if not default 0
		(( $ID_AUTOSTART )) && echo $ID_AUTOSTART > $FP_SETTINGS

		G_EXEC systemctl daemon-reload
	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# MENUS
	#/////////////////////////////////////////////////////////////////////////////////////
	TARGETMENUID=0
	# TARGETMENUID=0
	Menu_Main()
	{
		# Existing boot flag
		[[ -f $FP_SETTINGS ]] && ID_AUTOSTART=$(<$FP_SETTINGS)

		G_WHIP_MENU_ARRAY=(

			'' '●─ Local Terminal '
			'0' ': Manual login (default)'
			'7' ': Automatic login'
			'' '●─ Desktops '
			'16' ': LightDM login mask'
			'2' ': Automatic login'
			'' '●─ Browser Kiosk '
			'11' ': Chromium - Dedicated use without desktop'
			'' '●─ Media '
			'1' ': Kodi'
			'10' ': CAVA Spectrum'
			'' '●─ Gaming/Emulation '
			'6' ': Amiberry fast boot'
			'8' ': Amiberry standard boot'
			'9' ': DXX-Rebirth - Descent 1/2'
			'4' ': OpenTyrian'
			'' '●─ Other '
			'14' ': Custom - /var/lib/dietpi/dietpi-autostart/custom.sh'
			'5' ': DietPi-Cloudshell'

		)

		G_WHIP_BUTTON_CANCEL_TEXT='Exit'
		G_WHIP_DEFAULT_ITEM=$ID_AUTOSTART
		if G_WHIP_MENU "Current AutoStart Option: $ID_AUTOSTART\n\nNB: If your choice is not \"Local Terminal\", please ensure required software is installed (or selected for install) with DietPi-Software."
		then
			[[ $G_WHIP_RETURNED_VALUE ]] && ID_AUTOSTART=$G_WHIP_RETURNED_VALUE || return

			# Amiberry fast boot info
			if (( $ID_AUTOSTART == 6 ))
			then
				G_WHIP_MSG 'Amiberry fast boot:\nA highly optimised and tweaked boot mode.
This mode allows for a < 2.5 second boot on an RPi3, into Amiberry.\n\nIf you experience boot issues with this mode, please try the "standard boot" option.'

			# Chromium prompt for URL
			elif (( $ID_AUTOSTART == 11 ))
			then
				G_WHIP_DEFAULT_ITEM=$(sed -n '/^[[:blank:]]*SOFTWARE_CHROMIUM_AUTOSTART_URL=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
				G_WHIP_INPUTBOX 'Please enter a homepage URL to start with Chromium:
 - E.g.: https://dietpi.com' && G_CONFIG_INJECT 'SOFTWARE_CHROMIUM_AUTOSTART_URL=' "SOFTWARE_CHROMIUM_AUTOSTART_URL=$G_WHIP_RETURNED_VALUE" /boot/dietpi.txt

			# Custom: Create template and info
			elif [[ $ID_AUTOSTART == 14 && ! -f '/var/lib/dietpi/dietpi-autostart/custom.sh' ]]
			then
				G_EXEC mkdir -p /var/lib/dietpi/dietpi-autostart
				cat << '_EOF_' > /var/lib/dietpi/dietpi-autostart/custom.sh
#!/bin/bash
#---Examples---

# Chromium
#xinit chromium

# Desktop
#startx

# Print Hello
#echo 'Hello'

#---Put your code below this line---
_EOF_
				G_WHIP_MSG 'A template script has been created:\n - /var/lib/dietpi/dietpi-autostart/custom.sh\n
Please edit this file and enter the required commands you wish to launch. DietPi will then execute this script during boot.'
			fi

			# Apply selected boot option
			Apply_Boot_Index
		else
			TARGETMENUID=-1 # Exit
		fi
	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////
	# Start Menu
	if (( $INPUT == -1 ))
	then
		until (( $TARGETMENUID < 0 ))
		do
			G_TERM_CLEAR
			Menu_Main
		done

	# Apply boot index
	elif (( $INPUT >= 0 ))
	then
		ID_AUTOSTART=$INPUT
		Apply_Boot_Index
	fi

	#-----------------------------------------------------------------------------------
	exit
	#-----------------------------------------------------------------------------------
}
